import modelExtend from 'dva-model-extend'
import { query } from 'services/log'
import { pageModel } from 'utils/model'

export default modelExtend(pageModel, {

  namespace: 'log',

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/sys/log') {
          dispatch({
            type: 'query',
            payload: {
              ...location.query,
            }
          })
        }
      })
    },
  },

  effects: {
    * query({
      payload,
    }, { call, put }) {
      const data = yield call(query, payload)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(data.page.currPage) || 1,
              pageSize: Number(data.page.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      } else {
        throw data
      }
    },
    * changePage({ payload }, { call, put }) {
      const data = yield call(query, { page: payload.page, pageSize: payload.pageSize })
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(data.page.currPage) || 1,
              pageSize: Number(data.page.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      } else {
        throw data
      }
    },
  },
})
